document.addEventListener('DOMContentLoaded', () => {
    // 主题切换和分享功能
    const themeSwitch = document.getElementById('theme-switch');
    const body = document.body;
    const closeNoticeButton = document.getElementById('close-notice');
    const privacyNotice = document.getElementById('privacy-notice');
    const shareButton = document.getElementById('share-button');
    const shareNotification = document.getElementById('share-notification');
    const toggleFieldsBtn = document.getElementById('toggle-fields-btn');

    // 检查本地存储中的主题设置
    if (localStorage.getItem('theme') === 'dark') {
        document.documentElement.setAttribute('data-theme', 'dark');
        themeSwitch.checked = true;
    }

    // 主题切换功能
    themeSwitch.addEventListener('change', function() {
        if (this.checked) {
            document.documentElement.setAttribute('data-theme', 'dark');
            localStorage.setItem('theme', 'dark');
        } else {
            document.documentElement.removeAttribute('data-theme');
            localStorage.setItem('theme', 'light');
        }
    });

    // 隐私提示关闭按钮
    if (closeNoticeButton && privacyNotice) {
        closeNoticeButton.addEventListener('click', () => {
            privacyNotice.style.display = 'none';
            // 记住用户已关闭提示，使用localStorage存储状态
            localStorage.setItem('privacyNoticeClosed', 'true');
        });

        // 检查是否需要显示隐私提示
        if (localStorage.getItem('privacyNoticeClosed') === 'true') {
            privacyNotice.style.display = 'none';
        }
    }

    // 分享功能
    function shareURL() {
        // 创建临时文本区域
        const textarea = document.createElement('textarea');
        textarea.value = window.location.href;
        document.body.appendChild(textarea);
        
        // 选择并复制文本
        textarea.select();
        document.execCommand('copy');
        
        // 移除临时文本区域
        document.body.removeChild(textarea);
        
        // 显示分享成功通知
        shareNotification.classList.add('show');
        setTimeout(() => {
            shareNotification.classList.remove('show');
        }, 2000);
    }

    // 分享功能
    shareButton.addEventListener('click', shareURL);

    const jsonInput = document.getElementById('json-input');
    const processJsonBtn = document.getElementById('process-json-btn');
    const clearBtn = document.getElementById('clear-btn');
    const errorMessage = document.getElementById('error-message');
    const fieldsSection = document.getElementById('fields-section');
    const fieldsCheckboxesContainer = document.getElementById('fields-checkboxes');
    const exportExcelBtn = document.getElementById('export-excel-btn');
    const exportCsvBtn = document.getElementById('export-csv-btn');
    const copyNotification = document.getElementById('copy-notification');

    let parsedJsonData = null;
    let objectKeys = [];

    // Clear button functionality
    if (clearBtn) {
        clearBtn.addEventListener('click', () => {
            jsonInput.value = '';
            errorMessage.textContent = '';
            errorMessage.style.display = 'none';
            // 保持字段选择区域的显示状态
            fieldsCheckboxesContainer.innerHTML = '';
            parsedJsonData = null;
            objectKeys = [];
            // 重新设置字段选择区域的高度
            const jsonInputHeight = jsonInput.offsetHeight;
            fieldsCheckboxesContainer.style.height = `${jsonInputHeight}px`;
        });
    }

    // Process JSON button functionality
    if (processJsonBtn) {
        processJsonBtn.addEventListener('click', () => {
            const jsonString = jsonInput.value.trim();
            if (!jsonString) {
                displayError('请输入 JSON 数据。');
                return;
            }

            try {
                parsedJsonData = JSON.parse(jsonString);
                errorMessage.style.display = 'none';
                errorMessage.textContent = '';
                populateFieldCheckboxes();
            } catch (error) {
                displayError(`JSON 格式错误: ${error.message}`);
                fieldsSection.style.display = 'none';
                parsedJsonData = null;
            }
        });
    }

    function displayError(message) {
        errorMessage.textContent = message;
        errorMessage.style.display = 'block';
        // 不隐藏fields-section，保持界面布局一致
        // fieldsSection.style.display = 'none';
    }

    function populateFieldCheckboxes() {
        fieldsCheckboxesContainer.innerHTML = ''; // Clear previous checkboxes
        objectKeys = [];

        let sampleObject;
        if (Array.isArray(parsedJsonData) && parsedJsonData.length > 0) {
            // Use the first object in the array as sample
            sampleObject = parsedJsonData[0];
        } else if (typeof parsedJsonData === 'object' && parsedJsonData !== null) {
            // Use the single object
            sampleObject = parsedJsonData;
        } else {
            displayError('JSON 数据必须是对象数组或单个对象。');
            return;
        }

        // 递归获取所有字段路径
        const allFields = getAllFieldPaths(sampleObject);
        objectKeys = allFields;

        if (objectKeys.length === 0) {
            displayError('JSON 对象中没有可供选择的字段。');
            return;
        }


        
        // 设置fields-checkboxes的高度与json-input一致
        const jsonInputHeight = jsonInput.offsetHeight;
        fieldsCheckboxesContainer.style.height = `${jsonInputHeight}px`;
        fieldsCheckboxesContainer.style.overflowY = 'auto';

        // 创建层级字段显示
        objectKeys.forEach(fieldPath => {
            const checkboxDiv = document.createElement('div');
            checkboxDiv.classList.add('checkbox-item');
            
            // 计算缩进级别
            const level = (fieldPath.match(/\./g) || []).length;
            checkboxDiv.style.paddingLeft = `${level * 20}px`;

            const checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.id = `field-${fieldPath.replace(/\./g, '-')}`;
            checkbox.value = fieldPath;
            checkbox.checked = true; // Default to checked

            const label = document.createElement('label');
            label.htmlFor = `field-${fieldPath.replace(/\./g, '-')}`;
            // 只显示当前字段名称，不显示完整路径
            const fieldName = fieldPath.split('.').pop();
            label.textContent = fieldName;
            label.style.fontSize = level > 0 ? '0.9em' : '1em';
            label.style.color = level > 0 ? 'var(--text-secondary)' : 'var(--text-primary)';

            checkboxDiv.appendChild(checkbox);
            checkboxDiv.appendChild(label);
            fieldsCheckboxesContainer.appendChild(checkboxDiv);
        });

        // 不隐藏output-section，始终显示
        fieldsSection.style.display = 'block';
    }

    // 递归获取所有字段路径的函数
    function getAllFieldPaths(obj, prefix = '') {
        const paths = [];
        
        for (const key in obj) {
            if (obj.hasOwnProperty(key)) {
                const currentPath = prefix ? `${prefix}.${key}` : key;
                const value = obj[key];
                
                if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
                    // 如果是对象，递归获取子字段
                    paths.push(currentPath);
                    paths.push(...getAllFieldPaths(value, currentPath));
                } else if (Array.isArray(value) && value.length > 0) {
                    // 如果是数组，先添加数组字段本身
                    paths.push(currentPath);
                    // 然后检查数组第一个元素，如果是对象则递归获取其字段
                    const firstElement = value[0];
                    if (firstElement !== null && typeof firstElement === 'object' && !Array.isArray(firstElement)) {
                        paths.push(...getAllFieldPaths(firstElement, currentPath));
                    }
                } else {
                    // 如果是基本类型或空数组，直接添加
                    paths.push(currentPath);
                }
            }
        }
        
        return paths;
    }

    function getSelectedFields() {
        const selectedFields = [];
        fieldsCheckboxesContainer.querySelectorAll('input[type="checkbox"]:checked').forEach(checkbox => {
            selectedFields.push(checkbox.value);
        });
        return selectedFields;
    }

    function prepareDataForExport(selectedFields) {
        if (!parsedJsonData) return [];

        // 创建智能字段名映射
        const fieldNameMap = createSmartFieldNameMap(selectedFields);
        
        const dataToExport = [];
        const sourceData = Array.isArray(parsedJsonData) ? parsedJsonData : [parsedJsonData];

        sourceData.forEach(item => {
            // 检测是否存在数组字段（检查路径中是否包含数组）
            const hasArrayFields = selectedFields.some(fieldPath => {
                const keys = fieldPath.split('.');
                let current = item;
                
                for (let i = 0; i < keys.length - 1; i++) {
                    const key = keys[i];
                    if (current && current.hasOwnProperty(key)) {
                        current = current[key];
                        if (Array.isArray(current)) {
                            return true;
                        }
                    }
                }
                return false;
             });
            
            if (!hasArrayFields) {
                // 如果不存在数组字段，正常处理每个字段
                const row = {};
                selectedFields.forEach(fieldPath => {
                    const value = getNestedValue(item, fieldPath);
                    const displayName = fieldNameMap[fieldPath];
                    row[displayName] = value !== undefined && value !== null ? value : '';
                });
                dataToExport.push(row);
            } else if (selectedFields.length === 1) {
                // 如果只有一个字段且为数组，保持现有逻辑：将数组中每个值作为单独的行
                const fieldPath = selectedFields[0];
                const value = getNestedValue(item, fieldPath);
                const displayName = fieldNameMap[fieldPath];
                
                if (Array.isArray(value)) {
                    value.forEach(arrayItem => {
                        const row = {};
                        row[displayName] = arrayItem !== undefined && arrayItem !== null ? arrayItem : '';
                        dataToExport.push(row);
                    });
                } else {
                    const row = {};
                    row[displayName] = value !== undefined && value !== null ? value : '';
                    dataToExport.push(row);
                }
            } else {
                // 如果有多个字段且存在数组字段：为数组中每个元素创建一行
                // 找到数组字段的最大长度
                let maxArrayLength = 1;
                const arrayFieldValues = {};
                
                selectedFields.forEach(fieldPath => {
                    const value = getNestedValue(item, fieldPath);
                    if (Array.isArray(value)) {
                        arrayFieldValues[fieldPath] = value;
                        maxArrayLength = Math.max(maxArrayLength, value.length);
                    } else {
                        arrayFieldValues[fieldPath] = [value]; // 非数组字段包装成数组
                    }
                });
                
                // 为每个数组索引创建一行
                for (let i = 0; i < maxArrayLength; i++) {
                    const row = {};
                    selectedFields.forEach(fieldPath => {
                        const displayName = fieldNameMap[fieldPath];
                        const values = arrayFieldValues[fieldPath];
                        const value = i < values.length ? values[i] : '';
                        row[displayName] = value !== undefined && value !== null ? value : '';
                    });
                    dataToExport.push(row);
                }
            }
        });
        
        return dataToExport;
    }

    // 根据字段路径获取嵌套值的函数
    function getNestedValue(obj, path) {
        const keys = path.split('.');
        let current = obj;
        
        for (let i = 0; i < keys.length; i++) {
            const key = keys[i];
            if (current === null || current === undefined || !current.hasOwnProperty(key)) {
                return undefined;
            }
            current = current[key];
            
            // 如果当前值是数组，且还有后续路径，需要从数组元素中提取字段
            if (Array.isArray(current) && i < keys.length - 1) {
                const remainingPath = keys.slice(i + 1).join('.');
                const arrayValues = [];
                
                for (const item of current) {
                    if (item !== null && typeof item === 'object') {
                        const nestedValue = getNestedValue(item, remainingPath);
                        if (nestedValue !== undefined) {
                            arrayValues.push(nestedValue);
                        }
                    }
                }
                
                return arrayValues.length > 0 ? arrayValues : undefined;
            }
        }
        
        return current;
    }

    // 创建智能字段名映射函数
    function createSmartFieldNameMap(selectedFields) {
        const fieldNameMap = {};
        const fieldNameCounts = {};
        
        // 统计每个字段名出现的次数
        selectedFields.forEach(fieldPath => {
            const fieldName = fieldPath.split('.').pop();
            fieldNameCounts[fieldName] = (fieldNameCounts[fieldName] || 0) + 1;
        });
        
        // 为每个字段路径生成显示名称
        selectedFields.forEach(fieldPath => {
            const fieldName = fieldPath.split('.').pop();
            
            if (fieldNameCounts[fieldName] === 1) {
                // 如果字段名唯一，直接使用字段名
                fieldNameMap[fieldPath] = fieldName;
            } else {
                // 如果字段名重复，使用完整路径
                fieldNameMap[fieldPath] = fieldPath;
            }
        });
        
        return fieldNameMap;
    }

    // Toggle fields selection
    if (toggleFieldsBtn) {
        toggleFieldsBtn.addEventListener('click', () => {
            const fieldsCheckboxesContainer = document.getElementById('fields-checkboxes');
            const checkboxes = fieldsCheckboxesContainer.querySelectorAll('input[type="checkbox"]');
            checkboxes.forEach(checkbox => {
                checkbox.checked = !checkbox.checked;
            });
        });
    }

    // Export to Excel
    if (exportExcelBtn) {
        exportExcelBtn.addEventListener('click', () => {
            const selectedFields = getSelectedFields();
            if (selectedFields.length === 0) {
                alert('请至少选择一个字段导出。');
                return;
            }
            const data = prepareDataForExport(selectedFields);
            if (data.length === 0) {
                alert('没有数据可导出。');
                return;
            }

            const worksheet = XLSX.utils.json_to_sheet(data);
            const workbook = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
            XLSX.writeFile(workbook, 'exported_data.xlsx');
            showNotification('Excel 文件已导出！');
        });
    }

    // Export to CSV
    if (exportCsvBtn) {
        exportCsvBtn.addEventListener('click', () => {
            const selectedFields = getSelectedFields();
            if (selectedFields.length === 0) {
                alert('请至少选择一个字段导出。');
                return;
            }
            const data = prepareDataForExport(selectedFields);
            if (data.length === 0) {
                alert('没有数据可导出。');
                return;
            }

            // Manually construct CSV to ensure order and handling of complex data if needed
            const fieldNameMap = createSmartFieldNameMap(selectedFields);
            const headerRow = selectedFields.map(field => fieldNameMap[field]);
            let csvContent = headerRow.join(',') + '\n';

            data.forEach(row => {
                const rowValues = selectedFields.map(field => {
                    const displayName = fieldNameMap[field];
                    let value = row[displayName];
                    if (value === undefined || value === null) {
                        value = ''; // Handle undefined or null values as empty strings
                    }
                    if (typeof value === 'string' && (value.includes(',') || value.includes('\n') || value.includes('"'))) {
                        value = `"${value.replace(/"/g, '""')}"`; // Escape quotes and wrap in quotes
                    }
                    return value;
                });
                csvContent += rowValues.join(',') + '\n';
            });

            const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            const url = URL.createObjectURL(blob);
            link.setAttribute('href', url);
            link.setAttribute('download', 'exported_data.csv');
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            showNotification('CSV 文件已导出！');
        });
    }

    function showNotification(message) {
        if (copyNotification) {
            copyNotification.textContent = message;
            copyNotification.classList.add('show');
            setTimeout(() => {
                copyNotification.classList.remove('show');
            }, 2000);
        }
    }
});